package controller

import (
	"crypto/md5"
	"dsc-server/domain/dto"
	"dsc-server/pkg/model"
	"dsc-server/pkg/service"
	"encoding/hex"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gorm.io/gorm"
)

// TokenController Token控制器
type TokenController struct {
	BaseController
	DB           *gorm.DB
	TokenService *service.TokenService
}

// NewTokenController 创建TokenController实例
func NewTokenController(db *gorm.DB) *TokenController {
	return &TokenController{
		DB:           db,
		TokenService: service.NewTokenService(db),
	}
}

// Add 添加Token
func (ctrl *TokenController) Add(c *gin.Context) {
	var token model.Token
	if err := c.ShouldBind(&token); err != nil {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "参数绑定失败"))
		return
	}

	// 设置创建时间
	token.CreateTime = time.Now()

	result := ctrl.TokenService.Insert(&token)
	c.JSON(http.StatusOK, result)
}

// GetAll 获取所有Token
func (ctrl *TokenController) GetAll(c *gin.Context) {
	var tokens []model.Token
	if err := ctrl.DB.Where("is_deleted = 0").Find(&tokens).Error; err != nil {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "获取Token失败"))
		return
	}

	c.JSON(http.StatusOK, tokens)
}

// Delete 删除Token
func (ctrl *TokenController) Delete(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "ID参数错误"))
		return
	}

	result := ctrl.TokenService.DeleteById(uint(id))
	c.JSON(http.StatusOK, result)
}

// Generate 生成Token
func (ctrl *TokenController) Generate(c *gin.Context) {
	// 生成UUID
	u := uuid.New()

	// 计算MD5
	hash := md5.Sum([]byte(u.String()))
	token := hex.EncodeToString(hash[:])

	c.JSON(http.StatusOK, dto.Success(token))
}

// Auth 授权Token访问API分组
func (ctrl *TokenController) Auth(c *gin.Context) {
	tokenIdStr := c.PostForm("tokenId")
	groupIds := c.PostForm("groupIds")

	tokenId, err := strconv.ParseUint(tokenIdStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "TokenID参数错误"))
		return
	}

	result := ctrl.TokenService.Auth(uint(tokenId), groupIds)
	c.JSON(http.StatusOK, result)
}

// GetAuthGroups 获取Token授权的API分组
func (ctrl *TokenController) GetAuthGroups(c *gin.Context) {
	tokenIdStr := c.Param("tokenId")
	tokenId, err := strconv.ParseUint(tokenIdStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "TokenID参数错误"))
		return
	}

	groups, err := ctrl.TokenService.GetAuthGroups(uint(tokenId))
	if err != nil {
		c.JSON(http.StatusOK, dto.FailureMessage(nil, "获取授权分组失败"))
		return
	}

	c.JSON(http.StatusOK, groups)
}
